<script setup>
import { computed, ref } from 'vue'
import AddDividendRule from './components/AddDividendRule.vue'
import EditDividendRule from './components/EditDividendRule.vue'

const ruleOpts = ref([])
const rule = ref('')
const list = ref(null)

async function getRuleList() {
  const res = await window.api.getDividendAll()
  console.log(res)
  ruleOpts.value = res
  if (ruleOpts.value.length > 0) {
    rule.value = ruleOpts.value[0].dividend_id
    getRuleDetail()
  }
}
getRuleList()

async function getRuleDetail() {
  const res = await window.api.getDividendDetail(rule.value)
  console.log(res)
  list.value = res
}

function handleRuleChange() {
  getRuleDetail()
}

const ruleData = computed(() => {
  let data = null
  if (rule.value) {
    ruleOpts.value.forEach((item) => {
      if (item.dividend_id == rule.value) {
        data = item
      }
    })
  }
  return data
})

const showAddDividendRule = ref(false)

const EditData = computed(() => {
  return {
    ruleData: ruleData.value,
    ruleList: list.value
  }
})
const showEditDividendRule = ref(false)
</script>

<template>
  <div class="dividend-rate-page">
    <div class="top-filter-wrap">
      <div style="width: 300px; display: flex; align-items: center">
        <span style="flex-shrink: 0">分红规则名称</span>
        <el-select v-model="rule" placeholder="请选择分红规则" @change="handleRuleChange">
          <el-option
            v-for="item in ruleOpts"
            :key="item.dividend_id"
            :label="item.dividend_name"
            :value="item.dividend_id"
          ></el-option>
        </el-select>
      </div>
      <el-button type="primary" @click="showAddDividendRule = true">新增</el-button>
    </div>
    <div class="rule-name-box">
      <span>{{ ruleData?.dividend_name }}</span>
      <el-button v-if="rule" type="primary" @click="showEditDividendRule = true">编辑</el-button>
    </div>
    <el-table :data="list" style="width: 100%" border>
      <el-table-column prop="start_money" label="最小金额（含）" align="center"></el-table-column>
      <el-table-column prop="end_money" label="最大金额（不含）" align="center"></el-table-column>
      <el-table-column prop="ratio" label="分红比例（%）" align="center"></el-table-column>
      <el-table-column label="是否启用" align="center">
        {{ ruleData?.is_enable ? '是' : '否' }}
      </el-table-column>
    </el-table>
  </div>

  <!-- 规则 -->
  <AddDividendRule v-model:show="showAddDividendRule" @success="getRuleList" />

  <EditDividendRule v-model:show="showEditDividendRule" :data="EditData" @success="getRuleList" />
</template>

<style lang="scss" scoped>
.dividend-rate-page {
  .rule-name-box {
    padding-inline: 10px;
    margin-top: 20px;
    height: 50px;
    background-color: var(--el-bg-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
</style>
